<?php

require_once(dirname(__FILE__) . '/../classes/Deferred.php');
require_once(dirname(__FILE__) . '/../classes/DeferredList.php');
require_once(dirname(__FILE__) . '/../classes/multiCURL.php');

/**
 *
 * @staticvar string $queue
 * @param string $url
 * @param array $settings
 * @return Deferred 
 */
function Ajax($url, $settings = array()) {
    static $queue = NULL;
    if (NULL == $queue) {
        $queue = array();
        for($i = 0; $i < 10; $i++) {
            $queue[$i] = new TaskQueue(100);
        }
    }
    $settings = array_merge(array(
        'priority' => 5,
        'curl' => array(),
            ), $settings);

    $result = new Deferred();
    $curl = new multiCURL($url);
    $curl->setopt_array($settings['curl']);
    if(isset($settings['actions'])) {
        $curl->applyActions($settings['actions']);
    }
    $queue[$settings['priority']]->addTask($curl);
    $curl->addEventListener('onLoad', function(Event $event) use (&$result, $settings) {
                $event->target->removeEventListener($event->type, $event->callee); //needed???
                if (isset($settings['validation'])) {
                    foreach ($settings['validation'] as $validator) {
                        $is_valid = call_user_func($validator, array(
                            'result' => $event->target->result,
                            'info' => $event->target->info,
                            'url' => $event->target->url,
                            'error' => $event->target->error,
                                ));
                        if (!$is_valid) {
                            $event->target->error['validator_' . uniqid()] = $validator;
                        }
                    }
                }
                $return = array(
                    'result' => $event->target->result,
                    'info' => $event->target->info,
                    'url' => $event->target->url,
                    'error' => $event->target->error,
                );
                if (count($event->target->error) == 0) {
                    $result->callback($return);
                } else {
                    $result->errback($return);
                }
            });


    return $result;
}

/**
 *
 * @staticvar string $func
 * @param string $url
 * @param array $settings
 * @return Deferred
 */
function RetryAjax() {
    static $func = NULL;
    if (NULL == $func) {
        $func = createRetryFunction('Ajax', 20);
    }
    return call_user_func_array($func, func_get_args());
}
